import { ElMessage } from 'element-plus'

const webSocketMap: Record<string, any> = {}
// 发送消息
export function doSend(topic: string, message: string) {
  if (webSocketMap[topic]._socketOpen) {
    webSocketMap[topic].send(message)
  }
}

// 初始化websocket
export function contactSocket(topic: string, callback: Fn) {
  if ('WebSocket' in window && !webSocketMap[topic]) {
    webSocketMap[topic] = new WebSocket(import.meta.env.VITE_APP_WS_API + topic)

    webSocketMap[topic].onopen = function () {
      console.log('连接成功！')
      webSocketMap[topic]._socketOpen = true
    }

    webSocketMap[topic].onmessage = function (evt: any) {
      const received_msg = evt.data
      if (callback && received_msg !== 'conn_success') {
        let data: Record<string, any> | undefined
        try {
          data = JSON.parse(received_msg)
        }
        catch (error) {
          console.error(error)
          console.error('WebSocket返回值JSON序列化失败')
        }
        if (data) {
          callback(data)
          console.log('接受ws数据: ', data)
        }
      }
    }

    webSocketMap[topic].onclose = function () {
      console.log('连接关闭！')
    }

    webSocketMap[topic].onerror = function () {
      console.log('连接异常！')
    }
  }
}

// 断开连接
export function disContactSocket(topic: string) {
  webSocketMap[topic]?.close()
  delete webSocketMap[topic]
}
